﻿#region - Class details -
/*  
 *  Developer   : Wicus Botha
 *  Description : 
 *  History     : WB - 2007-12-18 - Created
 */
#endregion

using System;
using System.Data;
using System.Windows.Forms;
using IQ.Base.Services;
using IQ.BaseWindows;
using IQ.DbBase;
using SqlServerAdmin;

namespace IQ.DbA
{
    partial class FrmTables : Form
    {
        #region # Constructor #
        public FrmTables()
        {
            InitializeComponent();
        }
        #endregion

        #region - Private variables -
        private bool firstOpen = true;
        private SqlTable sqlTable = new SqlTable();
        #endregion

        #region - Private methods -
        private void openTable(string name)
        {
            sqlTable.Name = name;
            sqlTable.OpenTableData();
            refreshScreen();
        }
        private void loadCurrentTable(string name)
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                int iChanges = sqlTable.GetChangeCount();
                if (iChanges > 0)
                {
                    if (General.MesDlg("There were " + iChanges.ToString() + " changes made to " + sqlTable.Name +
                               ", apply changes?", 'C') == DialogResult.Yes)
                    {
                        sqlTable.ApplyUpdates();
                        if (sqlTable.LastError != "")
                            General.MesDlg("Update error: " + sqlTable.LastError, 'E');
                        else
                            openTable(name);
                    }
                    else
                        openTable(name);
                }
                else
                {
                    openTable(name);
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        private void refreshScreen()
        {
            imgFull.Image = (sqlTable.FullTable ? Properties.Resources.GreenDot : Properties.Resources.RedDot);
            grdTableData.CancelEdit();
            grdTableData.Columns.Clear();
            grdTableData.DataSource = sqlTable.ResultTable.DefaultView;
            grdFields.DataSource = sqlTable.TableFields;
            grdKeys.DataSource = sqlTable.TableKeys;
            grdKeysFields.DataSource = sqlTable.TableKeyFields;
        }
        private void firstLoadSetGridViews()
        {
            General.SetGridViewColumnsTo(grdFields, SqlConst.viewFields);
            General.SetGridViewColumnsTo(grdKeys, SqlConst.viewKeys);
            General.SetGridViewColumnsTo(grdKeysFields, SqlConst.viewKeysFields);
        }
        #endregion

        //#region - Public properties / variables - 
        //#endregion

        //#region - Public methods - 
        //#endregion

        #region - Bind Methods -
        #endregion

        #region - Form Events -
        // This region is for event handler methods that are called without the user knowing about it.
        // Such as the page loading.
        private void FrmTables_Load(object sender, EventArgs e)
        {
            if (DbHelper.CanConnect)
            {
                DataTable dtTables = DbHelper.Load_Table(SqlQueries.SqlTablesDetail);
                grdTables.DataSource = dtTables;
                dtTables.DefaultView.Sort = SqlQueries.Field_TableName;
                //
                General.SetGridViewColumnsTo(grdTables, SqlConst.viewTablesDetail);
                //
            }
            cbxOperator.SelectedIndex = 0;
        }
        private void grdFields_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            try
            {
                if ((e.RowIndex >= 0) &&
                     ((this.grdFields.Columns[SqlQueries.Field_ColumnIsIdentity].Index == e.ColumnIndex) ||
                      (this.grdFields.Columns[SqlQueries.Field_ColumnIsNullable].Index == e.ColumnIndex)))
                {
                    if (e.Value.ToString() == "1")
                        e.Value = "Yes";
                    else
                        e.Value = "";
                }
            }
            catch (Exception error)
            {
                Logging.Error("FrmTables, grdFields_CellFormatting" + "=" + error);
            }
        }
        private void grdFields_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            try
            {
                if (this.grdFields.Columns[SqlQueries.Field_ColumnIsIdentity].Index == e.ColumnIndex && e.RowIndex >= 0)
                {
                    //System.Drawing.Brush b = new System.Drawing.SolidBrush(e.CellStyle.BackColor);
                    //e.Graphics.FillRectangle(b,e.CellBounds.X,e.CellBounds.Y+1,e.CellBounds.Width-1,
                    //                        e.CellBounds.Height);
                    if (int.Parse(e.Value.ToString()) == 1)
                    {
                        e.Graphics.DrawImage(Properties.Resources.TickPlus, e.CellBounds.X + 3, e.CellBounds.Y + 3,
                                             Properties.Resources.TickPlus.Width, Properties.Resources.TickPlus.Height);
                        e.Handled = true;
                    }
                }
            }
            catch (Exception error)
            {
                Logging.Error("FrmTables, grdFields_CellPainting" + "=" + error);
            }
        }
        private void grdTableData_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            Logging.Error("FrmTables, grdTableData_DataError" + "=" + e.Context.ToString());

        }
        private void grdTableData_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (grdTableData.SelectedCells.Count > 1)
            {
                int firstColIndex = grdTableData.SelectedCells[0].ColumnIndex;
                bool doSum = (grdTableData.Columns[firstColIndex].ValueType != typeof(Char) && grdTableData.Columns[firstColIndex].ValueType != typeof(String)
                     && grdTableData.Columns[firstColIndex].ValueType != typeof(Boolean) && grdTableData.Columns[firstColIndex].ValueType != typeof(DateTime));
                decimal total = 0;
                int count = 0;
                int sumCnt = 0;
                foreach (DataGridViewCell dc in grdTableData.SelectedCells)
                {
                    if (dc.Value != DBNull.Value)
                    {
                        if (doSum && dc.ColumnIndex == firstColIndex)
                        {
                            total += Convert.ToDecimal(dc.Value);
                            sumCnt++;
                        }
                        count++;
                    }
                }
                stsCount.Text = "Cell count = " + count + "     ";
                if (doSum && sumCnt != 0)
                    stsCount.Text += " | Column: " + grdTableData.Columns[firstColIndex].HeaderText + " -> Sum = " + total.ToString("N") + " | Avg: " + (total / sumCnt).ToString("N");

            }
            else
            {
                stsCount.Text = "";
            }
        }
        #endregion

        #region - Control Methods -
        // This region is for event handler methods that are called knowingly by the user.
        // Such as a button being clicked.
        private void btnSave_Click(object sender, EventArgs e)
        {
            grdTableData.BindingContext[grdTableData.DataSource].EndCurrentEdit();
            loadCurrentTable(sqlTable.Name);
        }
        private void btnEmpty_Click(object sender, EventArgs e)
        {
            if (General.MesDlg("Empty table?", 'C') == DialogResult.Yes)
            {
                string result = sqlTable.EmptyTable();
                if (result != "")
                    General.MesDlg("Could not empty table; Error: " + result, 'E');
            }
        }
        private void btmMetaData_Click(object sender, EventArgs e)
        {
            SqlMdFileData.SaveMetaData();
            General.MesDlg("Meta data exported.", 'I');
            SqlMdFileData.Instance.RefreshFileData();
        }
        private void grdTables_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                loadCurrentTable(grdTables.Rows[e.RowIndex].Cells[0].FormattedValue.ToString());
                //
                if (firstOpen)
                {
                    firstLoadSetGridViews();
                    firstOpen = false;
                }
            } // Test Row & Col index

        }
        private void grdKeys_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (sqlTable.TableKeys.Columns.IndexOf(SqlQueries.Field_IndexId) >= 0)
                    sqlTable.FilterKeysData((short)sqlTable.TableKeys.Rows[e.RowIndex][SqlQueries.Field_IndexId]);
            }
        }
        private void grdTableData_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (grdTableData.Focused && e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                lblCurrentField.Text = sqlTable.ResultTable.Columns[e.ColumnIndex].ColumnName;
            }
        }
        private void chbFullTable_CheckedChanged(object sender, EventArgs e)
        {
            sqlTable.ForceFullTable = chbFullTable.Checked;
            loadCurrentTable(sqlTable.Name);
        }
        private void txtFilter_TextChanged(object sender, EventArgs e)
        {
            int colInd = grdTableData.CurrentCell.ColumnIndex;
            if (txtFilter.Text.Length > 0)
            {
                if (cbxOperator.SelectedIndex == 0)
                    sqlTable.FilterData(grdTableData.CurrentCell.OwningColumn.DataPropertyName, txtFilter.Text);
                else
                {
                    try
                    {
                        sqlTable.FilterData(grdTableData.CurrentCell.ColumnIndex, cbxOperator.Text, txtFilter.Text);
                    }
                    catch (Exception err)
                    {
                        General.MesDlg("Could not filter:" + err.Message, 'E');
                    }
                }
            }
            else
                sqlTable.FilterData(grdTableData.CurrentCell.ColumnIndex, cbxOperator.Text, "");
            grdTableData.CurrentCell = grdTableData.Rows[0].Cells[colInd];
        }
        #endregion

    }
}
